/*
笨方法学C的Page 117的习题26
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dbg.h"

#define MAX_LEN 100

int word_match(const char *string, const char *word);

int main(int argc, char *argv[])
{
	/* 
	目前完成了从文件中读取多行，去搜索匹配词，
	下一步要让程序接收可选参数，来决定匹配词的AND和OR搜索
	目前其实是只完成了OR
	*/
	
	int len;
	int count = 0; 				// 用于存放匹配合计次数
	char *str_ptr = (char *)malloc(sizeof(char)*MAX_LEN);
	// 注释单行文本输入语句 printf("Please input a sentence: ");
	char fname[MAX_LEN];   // 用于存放指定的文件名路径
	int i, j, k =0;

	printf("Please indicate the filename: ");
	scanf("%s", fname);

	FILE *fp;

	if((fp = fopen(fname, "r")) == NULL)
	{
		printf("The file cannot be opened\n");
		exit(-1);
	}
	
	// 每次while读取文件中的一行，直到文件末尾，fgets返回NULL
	while(fgets(str_ptr, MAX_LEN, fp) != NULL)
	{
		k++;	// 指明搜索到文件中的第几行
		
		// beware fgets will also read '\n' into the string
		// to change the last char from '\n' to '\0', i.e., to discard newline from the string
		len = strlen(str_ptr);
		if(len>0 && str_ptr[len-1] == '\n')
			str_ptr[len-1] = '\0';

		for(i = 1; i < argc; i++)
		{
			j = word_match(str_ptr, argv[i]);
			if(j != 0)
			{
				printf("'%s' is found for %d times in line%d of \"%s\"\n", argv[i], j, k, fname);
				count = count + j;
			}
			/*
			else
			{
				printf("'%s' is not found in line%d of \"%s\"\n", argv[i], k, fname);
			}*/
		}
	}
	
	// if no matching at all
	if(count == 0)
		printf("Nothing matched in \"%s\".\n", fname);

	
	return 0;
}


int word_match(const char *string, const char *word)
{
	int count = 0;
	int i = 0;
	

	// set temp position
	char *temp = word;
	
	// loop if string is not to the end
	while(*(string+i) != '\0')
	{
		if(*(string+i) == *temp)
		{
			temp++;		//if last char is equal, then try the next char in the word
		}
		else
		{
			temp = word;
		}
		i++;			// match or not, the source string moves on

		// to test word finishes matching, increase count and reset temp
		if(*temp == '\0')
		{
			count++;
			temp = word;	//reset temp, for next search
		}
	}

	return count;
}
